#pragma once
#include <bits/stdc++.h>
#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include <algorithm>
#include <cassert>
#include <fstream>
#include <mutex>
#include <jsoncpp/json/json.h>

#include "../comm/log.hpp"
#include "../comm/util.hpp"
#include "../comm/httplib.h"

// #include "oj_model.hpp"
#include "oj_model2.hpp"
#include "oj_view.hpp"

/*********************************
 * Control: 负责业务逻辑模块
 */
namespace ns_control
{
    using namespace ns_log;
    using namespace ns_util;
    using namespace ns_model;
    using namespace ns_view;

    using namespace httplib;

    const std::string DEFAULT_IP = "0.0.0.0";

    class Machine
    {
    public:
        Machine() : ip(DEFAULT_IP), port(0), load(0), mtx(nullptr)
        {}
        ~Machine() = default;
    public:
        void IncreaseLoad()
        {
            if(mtx) mtx->lock();
            ++load;
            if(mtx) mtx->unlock();
        }
        void DecreaseLoad()
        {
            if(mtx) mtx->lock();
            --load;
            if(mtx) mtx->unlock();
        }
        uint64_t Load()
        {
            uint64_t _load = 0;
            if(mtx) mtx->lock();
            _load = load;
            if(mtx) mtx->unlock();
            return _load;
        }
        void ResetLoad()
        {
            if(mtx) mtx->lock();
            load = 0;
            if(mtx) mtx->unlock();
        }
    public:
        std::string ip;         // 编译服务的ip
        uint16_t port;          // 编译服务的port
        uint64_t load;          // 编译服务的负载   
        std::mutex* mtx;
    };

    const std::string service_machine = "./conf/service_machine.conf"; 
    const std::string sep = ":";

    class LoadBlance
    {
    public:
        LoadBlance() 
        {
            assert(LoadConf(service_machine));
            LOG(INFO) << "加载 " << service_machine << " 成功\n";
        }
        ~LoadBlance() = default;
    public:
        bool LoadConf(const std::string& machine_conf)
        {
            std::ifstream in(machine_conf);
            if(!in.is_open())
            {
                LOG(FATAL) << "加载 " << machine_conf << " 失败\n";
                return false;
            }
            std::string line;
            while(getline(in, line))
            {
                std::vector<std::string> tokens;
                StringUtil::SplitString(line, &tokens, sep);
                if(tokens.size() != 2)
                {
                    LOG(WARNING) << "解析主机 " << line << " 失败\n";
                    continue;
                }
                Machine machine;
                machine.ip = tokens[0];
                machine.port = std::stoi(tokens[1]);
                machine.load = 0;
                machine.mtx = new std::mutex();

                online.emplace_back(machines.size());
                machines.emplace_back(machine);
            }
            in.close();
            return true;
        }

        bool SmartChoice(Machine** mac, int* idx)
        {
            /*********************
             * 负载算法
             *  1. 随机数+hash
             *  2. 轮询+hash
             */

            std::unique_lock<std::mutex> lock(mtx);
            int online_size = online.size();
            if(online_size == 0)
            {
                lock.unlock();
                LOG(FATAL) << "急急急，所有的后端编译主机已经离线！\n";
                return false;
            }

            *idx = online[0];
            *mac = &machines[*idx];
            uint64_t min_load = machines[*idx].Load();
            for (size_t i = 1; i < online_size; ++i)
            {
                uint64_t cur_load = machines[online[i]].Load();
                if(min_load > cur_load)
                {
                    min_load = cur_load;
                    *idx = online[i];
                    *mac = &machines[*idx];
                }
            }
            return true;
        }

        void OfflineMachine(int which)      // 下线指定主机
        {
            std::unique_lock<std::mutex> lock(mtx);
            for(auto iter = online.begin(); iter != online.end(); ++iter)
            {
                if(*iter == which)
                {
                    machines[which].ResetLoad();
                    online.erase(iter);
                    offline.emplace_back(which);
                    lock.unlock();
                    break;
                }
            }
        }

        void OnlineMachine()
        {
            std::cout << "OnlineMachine" << std::endl;
            // std::unique_lock<std::mutex> lock(mtx);
            mtx.lock();
            std::cout << "online.size" << online.size() << std::endl;
            std::cout << "offline.size" << offline.size() << std::endl;
            online.insert(online.end(), offline.begin(), offline.end());
            for(int i = 0; i < offline.size(); ++i) offline.pop_back();

            LOG(INFO) << "所有主机上线！\n";
            mtx.unlock();
        }

        void ShowMachines()
        {
            std::lock_guard<std::mutex> lock(mtx);
            std::cout << "当前在线主机列表: ";
            for(auto& id : online) std::cout << id << " ";
            std::cout << "\n当前离线主机列表: ";
            for(auto& id : offline) std::cout << id << " ";
            std::cout << "\n";
        }
    private:
        std::vector<Machine> machines;      // 记录提供编译的所有主机
        std::vector<int> online;            // 在线主机的id
        std::vector<int> offline;           // 离线主机的id
        std::mutex mtx;
    };

    class Control
    {
    public:
        Control() = default;
        ~Control() = default;
        
        void RecoveryMachines()
        {
            std::cout << "RecoveryMachines" << std::endl;
            load_blance_.OnlineMachine();
        }

        bool AllQuestions(std::string* html)
        {
            bool ret = true;
            std::vector<struct Question> all_questions;
            if(model_.GetAllQuestions(&all_questions))
            {
                std::sort(all_questions.begin(), all_questions.end(), [](const Question q1, const Question q2){
                    return std::stoi(q1.id) < std::stoi(q2.id);
                });
                // 获取题目成功，将题库数据渲染成网页
                view_.AllExpandHtml(all_questions, html);
            }
            else
            {
                *html = "获取题目失败，形成题目列表失败";
                ret = false;
            }
            return ret;
        }

        bool OneQuestion(std::string* html, const std::string& id)
        {
            bool ret = true;
            struct Question question;
            if(model_.GetOneQuestion(&question, id))
            {
                view_.OneExpandHtml(question, html);
            }
            else
            {
                *html = "获取题目: " + id + " 失败, 题目不存在";
                ret = false;
            }
            return ret;
        }
        
        void Judge(const std::string& id, const std::string& in_json, std::string* out_json)
        {
            // LOG(DEBUG) << in_json << "\nid: " << id << "\n";

            // 1. 根据题目编号获取题目属性字段
            Question question;
            model_.GetOneQuestion(&question, id);

            // 2. 对in_json反序列化, 获取用户code、input及测试用例
            Json::Value in_value;
            Json::Reader reader;
            reader.parse(in_json, in_value);
            std::string code = in_value["code"].asString();

            // 3. 拼接用户code、tail, 形成最终程序
            Json::Value compile_value;
            compile_value["input"] = in_value["input"].asString();
            compile_value["code"] = code + "\n" + question.tail;
            compile_value["cpu_limit"] = question.cpu_limit;
            compile_value["mem_limit"] = question.mem_limit;
            Json::FastWriter writer;
            std::string compile_string = writer.write(compile_value);

            // 4. 根据负载规则选择主机(一直选择, 直到主机可用, 否则全部挂掉)
            while (true)
            {
                int idx = 0;
                Machine* mac = nullptr;
                if(!load_blance_.SmartChoice(&mac, &idx))
                {
                    break;
                }

                // 5. 发起http请求, 获得判题结果
                Client client(mac->ip, mac->port);
                mac->IncreaseLoad();
                LOG(INFO) << "选择主机(id: " << idx << ", " << mac->ip << ":" << mac->port << ") 成功, 实时负载: "<< mac->Load() << "\n";
                if(auto res = client.Post("/compile_and_run", compile_string, "application/json;charset=utf-8"))
                {
                    // 6. 将结果返回out_json
                    if(res->status == 200)
                    {
                        *out_json = res->body;
                        mac->DecreaseLoad();
                        LOG(INFO) << "请求编译和运⾏服务成功..." << "\n";
                        break;
                    }
                    mac->DecreaseLoad();    
                }
                else
                {
                    // 请求失败
                    LOG(INFO) << "当前请求的主机(id: " << idx << ", " << mac->ip << ":" << mac->port << ") 可能已经离线\n";
                    load_blance_.OfflineMachine(idx);
                    load_blance_.ShowMachines();
                }
            }  
        }
    private:
        Model model_;
        View view_;
        LoadBlance load_blance_;
    };
}